<template>
  <div class="main">
    <div class="topTitle">{{title}}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin
          :show="spinShow"
        >
          <div class="content">
            <NForm
              ref="formRef"
              :rules="rules"
              :model="formValue"
              require-mark-placement="left"
              label-placement="left"
              :label-width="150"
              style="width: 1000rem"
              label-align="right"
            >
              <NSpace>
                <NFormItem
                  label="标题:"
                  path="title"
                >
                  <NInput
                    placeholder="请输入标题"
                    v-model:value="formValue.title"
                    clearable
                    class="commonWidth"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="摘要:"
                  path="noticeNotes"
                >
                  <NInput
                    type="textarea"
                    placeholder="请输入摘要"
                    v-model:value="formValue.noticeNotes"
                    clearable
                    class="commonWidth"
                  />
                </NFormItem>
              </NSpace>
              <!-- <NSpace>
                <NFormItem
                  label="排序:"
                  path="sortIndex"
                >
                  <NInputNumber
                    v-model:value="formValue.sortIndex"
                    style="flex: 1"
                    placeholder="请输入"
                    :show-button="true"
                    class="commonWidth"
                    :min="0"
                  />
                </NFormItem>
              </NSpace> -->
              <NSpace>
                <NFormItem
                  label="时间:"
                  path="startDate"
                >
                 <NDatePicker input-readonly
                    v-model:formatted-value="range"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetimerange"  default-time="00:00:00"
                    @update:formatted-value="changeDate"
                    class="commonWidth"
                  />
                </NFormItem>
              </NSpace>
              <!-- <NSpace>
                <NFormItem
                  label="结束时间:"
                  path="endDate"
                >
                 <NDatePicker input-readonly
                    placeholder="请输入"
                    style="flex: 1"
                    format="yyyy-MM-dd HH:mm:ss"
                    type="datetime"  default-time="00:00:00"
                    v-model:formatted-value="formValue.endDate"
                  />
                </NFormItem>
              </NSpace> -->
              <NSpace>
                <NFormItem
                  label="报名截止:"
                  path="endEnrollDate"
                >
                 <NDatePicker input-readonly
                    placeholder="请选择报名截止时间"
                    style="flex: 1"
                    type="datetime"  default-time="00:00:00"
                    format="yyyy-MM-dd HH:mm:ss"
                    class="commonWidth"
                    v-model:formatted-value="formValue.endEnrollDate"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="公告内容:"
                  path="endEnrollDate"
                >
                  <div style="border: 1px solid #dcdfe6; width: 600px; border-radius: 4px">
                    <toolbar
                      style="border-bottom: 1px solid #dcdfe6; width: 100%; border-radius: 4px"
                      :editor="editorRef"
                      :default-config="toolbarConfig"
                      mode="default"
                    />
                    <editor
                      v-model="formValue.noticeContent"
                      style="height: 200px; overflow-y: hidden"
                      :default-config="editorConfig"
                      mode="default"
                      @onCreated="onCreated"
                    />
                  </div>
                </NFormItem>
              </NSpace>
              <!-- 富文本编辑器 -->
              <!-- <div style="border: 1px solid #ccc; width: 100%">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editorRef"
                  :defaultConfig="toolbarConfig"
                  :mode="mode"
                />
                <Editor
                  style="height: 300rem; overflow-y: hidden"
                  v-model="formValue.noticeContent"
                  :defaultConfig="editorConfig"
                  :mode="mode"
                  @onCreated="handleCreated"
                />
              </div> -->
              
            </NForm>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          <template #icon>
            <img :src="VBackImg" style="width: 25rem; height: 25rem"/>
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="width: 78px" @click="confirm()" :loading="loading">
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>
</template>
<script setup lang="ts">
import { ref, reactive, nextTick, shallowRef, onMounted } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  NDatePicker,
  NSpin,
  useMessage,
  NImage,
  type FormInst,
  NInputNumber
} from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import { workFlow } from '@/enums/workFlow'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
// @ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
//@ts-ignore
import { IEditorConfig } from '@wangeditor/editor'
import { ApprovalFilled } from '@vicons/material'
import VBackImg from '@/assets/images/back.png'

const tags = useTagStore().tags
const message = useMessage()
const route = useRoute()
const title = ref('公告新增');
const noticeId = ref('');
const range = ref();
onMounted(()=>{
  if (route.path == '/volunteer/recruit/notice/edit') {
    title.value = '公告编辑';
    noticeId.value = route.query.id;
    getInfo();
  } else {
    title.value = '公告新增';
  }
})

const spinShow = ref(false)

const formValue = reactive<Record<string, any>>({
  title: '',
  // sortIndex: '',
  noticeNotes: '',
  noticeContent: '',
  fileIds: '',
  startDate: null,
  endDate: null,
  endEnrollDate: null,
  auditFlag: 0,
  listFlag: 0
});

const onCreated = (editor: any) => {
  editorRef.value = editor
  nextTick(() => {
    editorRef.value = editor // 一定要用 Object.seal() ，否则会报错
  })
  // editor.config.uploadHeaders = {'authentication':'111'};
}

const changeDate = (v: any) => {
  range.value = v
  formValue.startDate = v ? v[0] : null
  formValue.endDate = v ? v[1] : null
}

const rules = {
  title: {
    required: true,
    trigger: ['input'],
    validator(rule:any, value:any) {
      if (!value) {
        return new Error('请填写标题')
      }
      if (value.length > 100) {
        return new Error('公告标题字数不得超过100字')
      }
      return true
    }
  },
  noticeNotes: {
    required: true,
    trigger: ['input'],
    validator(rule:any, value:any) {
      if (!value) {
        return new Error('请填写摘要')
      }
      if (value.length > 500) {
        return new Error('摘要字数不得超过500字')
      }
      return true
    }
  },
  startDate: {
    required: true,
    trigger: ['input', 'blur'],
    validator(rule:any, value:any) {
      if (!value) {
        return new Error('请选择开始日期时间和结束日期时间')
      }
      return true
    }
  },
  endEnrollDate: {
    required: true,
    trigger: ['input', 'blur'],
    message: '请选择报名截止时间',
  }
}

const getInfo = async() => {
  const [error, res] = await sendRequest<HttpResponsePagination<any>>({
    module: 'volunteer',
    api: 'info',
    uri: {
      id: noticeId.value,
    }
  })
  if (error) throw new Error(error.message)
  if (res.code !== 0) throw new Error(res.msg)
  if (res.code == 0) {
    // range.value = v
    // form.startDate = v ? v[0] : null
    // form.endDate = v ? v[1] : null
    Object.assign(formValue, res.data)
    range.value = [formValue.startDate, formValue.endDate]
  }
}

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === route.path)
  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/volunteer/recruit/notice/index' })
  } else history.back()
}

// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const contentContent = ref()
const confirm = () => {
  if (noticeId.value) {
    formRef.value?.validate(async (error) => {
      if (error) return
      try {
        const [error, data] = await sendRequest({
          module: 'volunteer',
          api: 'update',
          override: {
            data: {
              id: noticeId.value,
              title: formValue.title,
              noticeNotes: formValue.noticeNotes,
              noticeContent: formValue.noticeContent,
              fileIds: formValue.fileIds,
              startDate: formValue.startDate,
              endDate: formValue.endDate,
              endEnrollDate: formValue.endEnrollDate,
              auditFlag: formValue.auditFlag,
              listFlag: formValue.listFlag,
            }
          }
        })

        if (error) throw new Error(error.message)
        if (data.code !== 0) throw new Error(data.msg)
        message.success('操作成功')
        goBack()
      } catch (error: any) {
        message.error(error.message)
      }
    })
  } else {
    formRef.value?.validate(async (error) => {
      if (error) return
      try {
        const [error, data] = await sendRequest({
          module: 'volunteer',
          api: 'save',
          override: {
            data: {
              title: formValue.title,
              noticeNotes: formValue.noticeNotes,
              noticeContent: formValue.noticeContent,
              fileIds: formValue.fileIds,
              startDate: formValue.startDate,
              endDate: formValue.endDate,
              endEnrollDate: formValue.endEnrollDate,
              auditFlag: formValue.auditFlag,
              listFlag: formValue.listFlag,
            }
          }
        });
        if (error) throw new Error(error.message)
        if (data.code !== 0) throw new Error(data.msg)
        message.success('操作成功')
        goBack()
      } catch (error: any) {
        message.error(error.message)
      }
    })
  }
}

//获取修改详情
const fileList: any = ref([])

const mode: any = ref('default')
const editorRef = shallowRef()
// 菜单配置
const toolbarConfig = ref({
  toolbarKeys: [
  'bold', // 加粗
'italic', // 斜体
'through', // 删除线
'underline', // 下划线
'color', // 文字颜色
'insertLink', // 插入链接
'fontSize', // 字体大小
'uploadImage', // 上传图片
// 'delIndent', // 缩进
// 'indent', // 增进
// 'deleteImage',//删除图片
// 'divider', // 分割线
// 'insertTable', // 插入表格
'justifyCenter', // 居中对齐
'justifyJustify', // 两端对齐
'justifyLeft', // 左对齐
'justifyRight', // 右对齐
'undo', // 撤销
// 'redo', // 重做
'clearStyle', // 清除格式
  ]
})

const editorConfig: Partial<IEditorConfig> = {
  placeholder: '请输入内容...',
  MENU_CONF: {}
}

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
  toolbarConfig.value = {
    excludeKeys: [
      '|',
      'emotion', //表情
      'insertVideo', //视频
      'uploadVideo',
      'group-video',
      'insertTable', //插入表格
      'codeBlock', //代码
      'fullScreen' //编辑器全屏
    ]
  }
}

//图片
//@ts-ignore
editorConfig.MENU_CONF['uploadImage'] = {
  fieldName: 'file',
  // server: '/api/common/file/uploadTest',
  server: '/common/annexFile/uploadFile',
  maxFileSize: 10 * 1024 * 1024, // 10M
  // headers: {
  //   Accept: 'text/x-json',
  // },

  // 跨域是否传递 cookie ，默认为 false
  // withCredentials: true,

  // 超时时间，默认为 10 秒
  // timeout: 5 * 1000, // 5 秒
  // 上传之前触发
  onBeforeUpload(file: File) {
    // TS 语法
    // onBeforeUpload(file) {    // JS 语法
    // file 选中的文件，格式如 { key: file }
    return file

    // 可以 return
    // 1. return file 或者 new 一个 file ，接下来将上传
    // 2. return false ，不上传这个 file
  },

  // 上传进度的回调函数
  onProgress(progress: number) {
    // TS 语法
    // onProgress(progress) {       // JS 语法
    // progress 是 0-100 的数字
    console.log('progress', progress)
  },

  // 单个文件上传成功之后
  onSuccess(file: File, res: any) {
    // TS 语法
    // onSuccess(file, res) {          // JS 语法
    console.log(`${file.name} 上传成功`, res)
  },

  // 单个文件上传失败
  onFailed(file: File, res: any) {
    // TS 语法
    // onFailed(file, res) {           // JS 语法
    console.log(`${file.name} 上传失败`, res)
  },

  // 上传错误，或者触发 timeout 超时
  onError(file: File, err: any, res: any) {
    // TS 语法
    // onError(file, err, res) {               // JS 语法
    console.log(`${file.name} 上传出错`, err, res)
  }
}
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 20rem 0 180rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        height: 130rem;
        background: #e1e1e1;
        padding: 15rem 20rem;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: auto;
          min-width: 150rem;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 0 10rem;
          margin-right: 20rem;
        }
      }
    }
  }
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  width: 100%;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  padding: 10rem;
  display: flex;
  align-items: center;
  margin-top: 10rem;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
